package com.cy.store.controller;

import com.cy.store.controller.ex.*;
import com.cy.store.entity.User;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.InsertException;
import com.cy.store.service.ex.UsernameDuplicateException;
import com.cy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/users")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;
    /*@RequestMapping("/reg")
    public JsonResult<Void> reg(User user){
        //创建响应结果对象
        JsonResult<Void> result = new JsonResult<>();

        try {
            userService.reg(user);
            result.setState(200);
            result.setMessage("用户注册成功");
        } catch (UsernameDuplicateException e) {
            result.setState(4000);
            result.setMessage("用户名被占用");
        }catch (InsertException e) {
            result.setState(5000);
            result.setMessage("系统繁忙，请稍后再试");
        }
        return result;
    }*/
    @RequestMapping("/reg")
    public JsonResult<Void> reg(User user){
        userService.reg(user);
        return new JsonResult<>(OK);
    }


    //用户登录功能
    @RequestMapping("/login")
    public JsonResult<User> login(String username, String password, HttpSession session){
        User data = userService.login(username, password);
        //将数据保存到session中
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());

        System.out.println(getUidFromSession(session));
        System.out.println(getUsernameFromSession(session));

        return new  JsonResult<User>(OK, data);
    }


    //修改密码
    @RequestMapping("/change_password")
    public JsonResult<Void> changePassword(String oldPassword,String newPassword,HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changePassword(uid,username,newPassword,oldPassword);
        return new JsonResult<>(OK);
    }

    //根据uid查询user数据
    @RequestMapping("/get_by_uid")
    public JsonResult<User> getById(HttpSession session){
        User data = userService.getByUid(getUidFromSession(session));
        return new JsonResult<>(OK,data);
    }

    @RequestMapping("/change_info")
    public JsonResult<Void> changeInfo(User user,HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.updateInfo(uid,username,user);
        return new JsonResult<>(OK);
    }

    //设置上传文件的最大值
    public static final int AVATAR_MAX_SIZE = 10*1024*1024;
    //限制上传文件的类型
    public static final List<String> AVATAR_TYPE = new ArrayList<>();
    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/jpg");
        AVATAR_TYPE.add("image/gif");
    }
    @RequestMapping("/change_avatar")
    public JsonResult<String> changeAvatar(HttpSession session,@RequestParam("file") MultipartFile file){
        //判断文件是否为空
        if (file.isEmpty()){
            throw new FileEmptyException("文件不能为空");
        }
        //判断文件类型
        String contentType = file.getContentType();
        if (!AVATAR_TYPE.contains(contentType)){
            throw new FileTypeException("文件类型不支持");
        }
        //判断文件大小是否超过限制
        if (file.getSize()>AVATAR_MAX_SIZE){
            throw new FileSizeException("文件大小不能超出10M");
        }
        //上传文件 ../upload/文件.png
        String parent = session.getServletContext().getRealPath("/upload");
        //file对象指向这个路径,file是否存在
        File dir = new File(parent);
        //不存在则创建目录
        if (!dir.exists()){
            dir.mkdir();
        }
        //获取到这个文件的名字，用UUID生成一个新的名字
        String originalFilename = file.getOriginalFilename();
        System.out.println("originalFilename = " + originalFilename);
        //截取文件的后缀名
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        //使用UUID来生成新的文件名称
        String fileName = UUID.randomUUID().toString().toUpperCase()+suffix;
        //新建一个空文件,将上传的图片和名字写入到空文件中
        File dest = new File(dir,fileName);
        try {
            file.transferTo(dest);//将file文件中的数据写到dest中
        } catch (FileStateException e) {
            throw new FileStateException("文件状态异常");
        }catch (IOException e) {
            throw new FileUploadException("文件读写异常");
        }
        //获取当前用户的uid
        Integer uid = getUidFromSession(session);
        //获取当前用户的username
        String username = getUsernameFromSession(session);
        //返回头像的路径
        String avatar = "/upload/"+fileName;
        userService.changeAvatar(uid,avatar,username);
        //返回头像的路径给前端,将来用于头像的展示
        return new JsonResult<>(OK,avatar);
    }
}
